<template>
  <div class="logon">
    <h1>欢迎登录</h1>
    <form @submit.prevent="handleLogin">
      <div class="form-item">
        <label for="username" class="form-label">用户名：</label>
        <input type="text" id="username" v-model="username" class="form-input" required />
      </div>
      <div class="form-item">
        <label for="password" class="form-label">密码：</label>
        <div class="password-container">
          <input
            :type="showPassword ? 'text' : 'password'"
            id="password"
            v-model="password"
            class="form-input"
            required
          />
          <button
            type="button"
            class="toggle-password"
            @click="togglePasswordVisibility"
          >
            {{ showPassword ? '隐藏' : '显示' }}
          </button>
        </div>
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<!--关键修改：-->
<!--在 data 中为 username 和 password 提供了默认值：-->
<!--使用 v-model 将输入框与 data 中的 username 和 password 绑定，这样页面加载时会自动填充默认值：-->
<script>
import axios from 'axios'
import { mapMutations } from 'vuex'

export default {
  name: 'Logon',
  data () {
    return {
      username: 'admin', // 默认填充用户名为 admin
      password: 'admin123', // 默认填充密码为 password
      showPassword: false // 控制密码是否可见
    }
  },
  mounted () {
    console.log('mounted process')
    console.log(this.$store) // 如果为 undefined，则说明未注册 Vuex
  },
  methods: {
    ...mapMutations(['setAccessToken', 'setRefreshToken']), // Vuex 绑定 mutations
    togglePasswordVisibility () {
      this.showPassword = !this.showPassword
    },
    async handleLogin () {
      try {
        // 发起登录请求
        const response = await axios.post(
          process.env.API_ROOT + '/auth_rbac/login_rbac_plain',
          {
            username: this.username,
            password: this.password
          },
          {
            headers: {
              accept: 'application/json',
              'Content-Type': 'application/json'
            }
          }
        )

        // 成功返回处理
        // eslint-disable-next-line camelcase
        const { access_token, refresh_token, expire } = response.data

        // // 保存到 Vuex
        // this.setAccessToken(access_token)
        // this.setRefreshToken(refresh_token)
        // 保存到 Vuex
        this.$store.commit('setAccessToken', access_token) // 直接提交 Vuex mutation
        this.$store.commit('setRefreshToken', refresh_token)
        this.$store.commit('setUsername', this.username) // 保存用户名

        // 保存到 LocalStorage
        localStorage.setItem('access_token', access_token)
        localStorage.setItem('refresh_token', refresh_token)
        localStorage.setItem('token_expire', expire)
        localStorage.setItem('username', this.username) // 保存用户名

        alert('登录成功！')
        console.log('Access Token:', access_token)
        console.log('Refresh Token:', refresh_token)

        // 跳转到首页
        this.$router.push('/dashboard')
      } catch (error) {
        // 错误返回处理
        if (error.response && error.response.data.message) {
          alert(`登录失败：${error.response.data.message}`)
        } else {
          console.error('未知错误：', error)
          alert('登录失败，请检查网络或联系管理员')
        }
      }
    }
  }
}
</script>

<style scoped>
.logon {
  text-align: center;
}

form {
  display: inline-block;
  margin-top: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.form-label {
  width: 80px; /* 确保 label 宽度一致 */
  text-align: right; /* 文本右对齐 */
  margin-right: 10px;
}

.form-input {
  flex: 1;
  padding: 8px;
}

.password-container {
  display: flex;
  align-items: center;
  flex: 1;
}

.toggle-password {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}

.toggle-password:hover {
  background-color: #368f6a;
}

button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #368f6a;
}
</style>
